package com.zq.vaccinum.controller;

import com.zq.vaccinum.constant.Constants;
import com.zq.vaccinum.domain.JsonResult;
import com.zq.vaccinum.service.ex.ServiceException;
import com.zq.vaccinum.service.ex.user.*;
import org.apache.ibatis.cache.CacheException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

/*
* 统一异常处理
* */
@ControllerAdvice
public class BaseController {
    // 操作成功状态码
    public static final int OK = Constants.SUCCESS;

    // 操作失败
    // 请求处理方法，返回值就是需要传递给前端的数据
    // 自动将异常对象传递给此方法的参数列表上
    // 当项目中产生了异常，会被统一拦截到此方法中，此方法充当请求处理方法，方法的返回值直接给前端
    // 用于统一处理抛出的异常
    /*
    * 当出现异常后,调用这个方法
    * */
    @ExceptionHandler(ServiceException.class)
    public JsonResult handleException(Throwable e){
        JsonResult result = new JsonResult(e);
        if (e instanceof UsernameDuplicatedException){
            result.setCode(4000);
            result.setMessage("用户名被占用");
        }else if (e instanceof UserNotFoundException){
            result.setCode(5001);
            result.setMessage("用户数据不存在");
        }else if (e instanceof UserPasswordNotMatchException){
            result.setCode(5002);
            result.setMessage("账号密码不匹配");
        } else if (e instanceof InsertException){
            result.setCode(5000);
            result.setMessage("用户注册过程中产生未知的异常");
        }else if (e instanceof CacheException){
            result.setCode(5003);
            result.setMessage("验证码错误");
        }else if (e instanceof UnauthenticatedException){
            result.setCode(5004);
            result.setMessage("用户未登录");
        }else if (e instanceof UsernameNotFoundException){
            result.setCode(5005);
            result.setMessage("用户名或者密码错误");
        }else if (e instanceof CaptchaExpireException){
            result.setCode(Constants.ERROR);
            result.setMessage("验证码已失效");
        }
        return result;
    }
}
